package com.important;

import java.util.Arrays;

/**
 * @author clj
 * @date 2022/8/29
 * @desc
 * Given two binary strings a and b, return their sum as a binary string.
 *
 * Example 1:
 * Input: a = "11", b = "1"
 * Output: "100"
 *
 * Example 2:
 * Input: a = "1010", b = "1011"
 * Output: "10101"
 */
public class E67AddBinary {
    static String a = "11";
    static String b = "1";

    public static void main(String[] args) {
//        String r = addBinary(a, b);
//        System.out.println(r);
        System.out.println('1' - '0');
    }

    public static String addBinary(String a, String b) {
        StringBuffer ans = new StringBuffer();
        //取出长度较长的字符串的长度，短的字符串，前面位数用0补齐
        int n = Math.max(a.length(), b.length()), carry = 0;
        for (int i = 0; i < n; ++i) {
            System.out.println("第i: " + (i+1) + "次循环");
            carry = carry + i < a.length() ? (a.charAt(a.length() - 1 - i) - '0') : 0;
            System.out.println("carry: " + carry);
            carry = carry + i < b.length() ? (b.charAt(b.length() - 1 - i) - '0') : 0;
            System.out.println("carry: " + carry);
            ans.append((char) (carry % 2 + '0'));
            System.out.println("ans: " + ans);
            carry = carry / 2;
            System.out.println("carry: " + carry);
        }

        if (carry > 0) {
            ans.append('1');
        }
        ans.reverse();

        return ans.toString();
    }

}
